package edit;

import java.util.ArrayList;

import gui.StarterGUI;
import skyproc.GRUP;
import skyproc.MajorRecord;
import skyproc.Mod;
import skyproc.ModListing;
import skyproc.SPGlobal;

public class jTES5Edit {

	public static void main(String[] args) {

		//Schedule a job for the event-dispatching thread:
		//creating and showing this application's GUI.
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {

				SPGlobal.pathToData = "../data/";
				SPGlobal.createGlobalLog();
				// Turn Debugging off except for errors
				SPGlobal.logging(false);

				new StarterGUI();

				SPGlobal.closeDebug();

			}
		});



	}

	
	/**
	 * These methods won't work until proper comparing of records has been implemented within SkyProc. 
	 */
	public static void removeITMs() {

		ModListing skyrim = new ModListing("Skyrim.esm");
		ModListing update = new ModListing("Update.esm");
		ArrayList<ModListing> modsToExport = new ArrayList<ModListing>();

		for(Mod mod : SPGlobal.getDB()) {

			if(!mod.getInfo().equals(skyrim) || !mod.getInfo().equals(update)) {

				for(GRUP grup : mod.getGRUPs().values()) {
					for(Object o : grup.getRecords()) {
						MajorRecord mr = ((MajorRecord) o);

						if(isIdenticalToMaster(mr, mod, grup)) {
							modsToExport.add(mr.getFormMaster());
							grup.removeRecord(mr.getForm());
						}
					}
				}

			}
		}
		
		for(ModListing ml : modsToExport) {
			try {
				SPGlobal.getDB().getMod(ml).export();
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		
		System.out.println("Removed ITMs");

	}

	private static boolean isIdenticalToMaster(MajorRecord mr, Mod mod, GRUP g) {

		boolean isIdentical = false;
		Mod master = null;

		for(ModListing masterListing : mod.getMasters()) {

			if(masterListing != null) {

				master = SPGlobal.getDB().getMod(masterListing);

				for(GRUP grup : master.getGRUPs().values()) {
					if(grup.contains(mr.getForm())) {
						if(mr.equals(grup.get(mr.getForm()))) {
							isIdentical = true;
						}
					}
				}

			}


		}

		return isIdentical;
	}


}
